<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

JFX::checkAdminPermsRedirect('core', 'perm_edit_page');


$CONFIG->debug = true;


$VIEW->template = 'admin-thickbox.tpl';

if((int) get('page', 0) <= 0){
    // editing the default page
    $pageid = (int) $DB->oneValue($CONFIG->dbprefix.'pages', 'id', 'is_default = 1');
    $_GET['page'] = $pageid;
}else{
    $pageid = (int) get('page');
    if($DB->countRows($CONFIG->dbprefix.'pages', "id = '{$pageid}'")==0){
        $pageid = (int) $DB->oneValue($CONFIG->dbprefix.'pages', 'id', 'is_default = 1');
    }
}


$childPageIds = JFX_EditPage_FindChildIds(JFX::getPageTree($pageid, $USER->workspace));
$childPageIds[] = $pageid;



$js = '

JFXEditPageParentIds = Array("'.implode('","', $childPageIds).'");
$(document).ready(function(){
    $("#jfx-edit-page-tree").treeview({
        persist: "location",
        collapsed: true,
        unique: true
    });
    $("#jfx-edit-page-tree a").click(function(){
        for(var i=0; i<JFXEditPageParentIds.length; i++){
            if(JFXEditPageParentIds[i] == this.id.replace("page_", "")){
                alert("Cannot assign the page to a child of itself!");
                return;
            }
        }
        $("#parent-id").get(0).value = this.id.replace("page_", "");
        $("#disabled-parent").get(0).value = $(this).text();
    });

    $("#jfx-mirror-page-tree").treeview({
        persist: "location",
        collapsed: true,
        unique: true
    });
    $("#jfx-mirror-page-tree a").click(function(){
        $("#mirror-id").get(0).value = this.id.replace("page_mirror_", "");
        $("#disabled-mirror").get(0).value = $(this).text();
    });

    $("#use-mirror_component").click(function(){
        setTimeout(JFXEditPageUseMirrorToggle, 200);
        //return false;
    });

    JFXEditPageUseMirrorToggle();


});




function JFXEditPageUseMirrorToggle(){
    var isChecked = $("#use-mirror input[type=checkbox]").get(0).checked;
    if(isChecked){
        $("#mirror-page-tree").slideDown("slow");
        $("#disabled-mirror").slideDown("slow");
    }else{
        $("#mirror-page-tree").slideUp("slow");
        $("#disabled-mirror").slideUp("slow");
    }
}

';

$VIEW->addJs($js);

if(Antz_IntelliForm::submitted('edit-page')){
    $error = false;
    $slug = post('slug');
    $published = post('published');
    $default = post('default');
    $title = post('title');
    $menu = post('menu');
    $parentid = (int) post('parent');
    $mirrorid = (int) post('mirror');
    $useMirror = (int) post('useMirror');

    if($DB->countRows($CONFIG->dbprefix.'pages', "id = '{$parentid}' AND workspace_id = '{$USER->workspace}'")==0){
        if($parentid == 0 && $pData['parent_id'] == 0){
            // the only way to change to a parent_id of 0 is by assigning the domain
        }else{
            $error = true;
            JFX::addError($this->lang('invalid_parent_page'));
        }
    }else{
        // load the domain for our slug matching
        $parentData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$parentid}'");
        $domainid = $parentData['domain_id'];
    }

    if($slug == trim($CONFIG->moduleServerFolder, '/') ||
       $slug == trim($CONFIG->moduleCssFolder, '/') ||
       $slug == trim($CONFIG->moduleJsFolder, '/') ||
       $slug == trim($CONFIG->moduleImageFolder, '/') ||
       $slug == 'jfx'){
       JFX::addError($this->lang('slug_reserved'));
       $error = true;
    }

    if($useMirror > 0 && $DB->countRows($CONFIG->dbprefix.'pages', "id = '{$mirrorid}'")==0){
        $error = true;
        JFX::addError($this->lang('invalid_mirror_id', $mirrorid));
    }

    if($DB->countRows($CONFIG->dbprefix.'pages', "slug = '{$slug}' AND id != '{$pageid}' AND domain_id = '{$domainid}' AND workspace_id = '{$USER->workspace}'")>0){
        $error = true;
        JFX::addFormError('slug', $this->lang('slug_already_in_use'));
        JFX::addError($this->lang('slug_already_in_use'));
    };

    if(!$error){
        $dbParams = array(
            'modified_tstamp' => time(),
            'slug' => $slug,
            'is_published' => $published,
            'is_default' => $default,
            'parent_id' => $parentid,
            'mirror_id' => $mirrorid,
            'domain_id' => $domainid
        );

        if($default == 1) $DB->query("UPDATE {$CONFIG->dbprefix}pages SET is_default = 0 WHERE domain_id = '{$domainid}' AND workspace_id = '{$USER->workspace}'");
        $LANG->updateContent('core', 'heading', 'jfxpage-'.$pageid, $title, '', $USER->workspace);
        $LANG->updateContent('core', 'page_menu','jfxpage-'.$pageid, $menu, '', $USER->workspace);
        $DB->update($CONFIG->dbprefix.'pages', $dbParams, "id = '{$pageid}'");
        JFX::addSuccess($this->lang('page_update_success'));
    }

}

$pData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}pages WHERE id = '{$pageid}'");

$pagesRecursive = JFX::getPageTree(0, $USER->workspace);

$tree = '<ul id="jfx-edit-page-tree">'.JFX_EditPage_MakeTree($pagesRecursive, $childPageIds, 'page_').'</ul>';
$mirrorTree = '<ul id="jfx-mirror-page-tree">'.JFX_EditPage_MakeTree($pagesRecursive, $childPageIds, 'page_mirror_').'</ul>';

$parentTitle = $LANG->getContent('core', 'heading', $pData['parent_id']);
$mirrorTitle = $LANG->getContent('core', 'heading', $pData['mirror_id']);

//$DB->debug(true);
//$DB->showErrors(true);

$lang = array(
    'title' => $LANG->getContent('core', 'heading', 'jfxpage-'.$pageid, '', $USER->workspace),
    'menu' => $LANG->getContent('core', 'page_menu', 'jfxpage-'.$pageid, '', $USER->workspace)
);

//$DB->debug(false);
//$DB->showErrors(false);

if($pData['parent_id']!=0){
    $default = array(
        'name' => 'default',
        'value' => '1',
        'label' => $this->lang('is_default'),
        'type' => 'checkbox',
        'checked' => post('default', $pData['is_default'])
    );
    $parent = array(
        'name' => 'parent',
        'value' => post('parent', $pData['parent_id']),
        'type' => 'hidden',
        'id' => 'parent-id',
        'label' => ''
    );
    $parentList = array(
        'type' => 'longtag',
        'tag' => 'div',
        'class' => 'form-field',
        'id' => 'parent-page-tree',
        'content' => '<label>'.$LANG->get('core', 'page_parent').'</label>
<div class="input-area">'.$tree.'</div>'
    );
    $selectedParent = array(
        'name' => 'disabled_parent',
        'value' => $parentTitle,
        'type' => 'text',
        'id' => 'disabled-parent',
        'extra' => array(
            array(
                'command' => 'addAttribute',
                'params' => array(
                    '"disabled"', '"disabled"'
                )
            )
        ),
        'label' => 'Selected Parent'
    );
    $legend = $LANG->get('core', 'page_legend');
}else{
    $selectedParent = array();
    $default = array();
    $parent = array();
    $parentList = array();
    $legend = $LANG->get('core', 'domain_legend');
}

$formFields = array(
    $selectedParent,
    $parent,
    $parentList,
    array(
        'name' => 'slug',
        'value' => post('slug', $pData['slug']),
        'label' => $this->lang('page_slug')
    ),
    array(
        'name' => 'title',
        'value' => post('title', $lang['title']),
        'label' => $this->lang('page_title'),
    ),
    array(
        'name' => 'menu',
        'value' => post('menu', $lang['menu']),
        'label' => $this->lang('page_menu')
    ),
    array(
        'name' => 'published',
        'value' => '1',
        'label' => $this->lang('is_published'),
        'type' => 'checkbox',
        'checked' => post('published', $pData['is_published'])
    ),
    $default
);

$mirrorCheck = array(
    'name' => 'useMirror',
    'value' => 1,
    'label' => $this->lang('use_mirror'),
    'type' => 'checkbox',
    'checked' => (bool) post('useMirror', ($pData['mirror_id'] == 0) ? false : true),
    'id' => 'use-mirror'
);
$mirror = array(
    'name' => 'mirror',
    'value' => post('mirror', $pData['mirror_id']),
    'type' => 'hidden',
    'id' => 'mirror-id',
    'label' => ''
);
$mirrorList = array(
    'type' => 'longtag',
    'tag' => 'div',
    'class' => 'form-field',
    'id' => 'mirror-page-tree',
    'content' => '<label>'.$LANG->get('core', 'page_mirror').'</label>
    <div class="input-area">'.$mirrorTree.'</div>'
);
$selectedMirror = array(
    'name' => 'disabled_mirror',
    'value' => $mirrorTitle,
    'type' => 'text',
    'id' => 'disabled-mirror',
    'extra' => array(
        array(
            'command' => 'addAttribute',
            'params' => array(
                '"disabled"', '"disabled"'
            )
        )
    ),
    'label' => $this->lang('selected_mirror')
);

if($pData['parent_id']!=0){

    $formFields[] = $mirrorCheck;
    $formFields[] = $mirror;
    $formFields[] = $mirrorList;
    $formFields[] = $selectedMirror;
    
}

$formFields[] = array(
    'name' => 'submitBtn',
    'value' => $this->lang('edit_page_submit'),
    'label' => '&nbsp;',
    'type' => 'submit'
);

$form = JFX::makeRapidForm($formFields, $legend, 'edit-page');

$SMARTY->assign('form', $form->render());

echo $SMARTY->fetch('admin/ajax/edit-page.tpl');


function JFX_EditPage_MakeTree($arr, $childPageIds, $idprefix){
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $returnString = '';
    foreach($arr as $k=>$v){

        if(!in_array($v['id'], $childPageIds)) $link = '<a href="javascript: void(null)" id="'.$idprefix.$v['id'].'">'.$LANG->getContent('core', 'heading', $v['id']).'</a>';
        else $link = $LANG->getContent('core', 'heading', $v['id']);
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_EditPage_MakeTree($v['subpages'], $childPageIds, $idprefix).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li>'.$link.$subpages.'</li>';
    }

    return $returnString;
}



function JFX_EditPage_FindChildIds($pages){
    $childIds = array();
    foreach($pages as $k=>$v){
        $childIds[] = $v['id'];
        if(count($v['subpages'])>0){
            $childIds = array_merge($childIds, JFX_EditPage_FindChildIds($v['subpages']));
        }
    }
    return $childIds;
}


